package com.yidingdui.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint("/ws/task-notification/{userId}")
public class TaskNotificationEndpoint {
    
    static {
        log.info("TaskNotificationEndpoint WebSocket端点已注册: /ws/task-notification/{userId}");
    }

    private static final Map<String, Session> userSessions = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        userSessions.put(userId, session);
        log.info("WebSocket连接建立: userId={}, sessionId={}", userId, session.getId());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.debug("收到WebSocket消息: {}", message);
        // 可以处理客户端发送的消息
    }

    @OnClose
    public void onClose(Session session, @PathParam("userId") String userId) {
        userSessions.remove(userId);
        log.info("WebSocket连接关闭: userId={}, sessionId={}", userId, session.getId());
    }

    @OnError
    public void onError(Session session, Throwable error, @PathParam("userId") String userId) {
        log.error("WebSocket错误: userId={}, sessionId={}", userId, session.getId(), error);
        userSessions.remove(userId);
    }

    /**
     * 发送任务通知给指定用户
     */
    public static void sendTaskNotification(String userId, String taskId, String status, String message) {
        Session session = userSessions.get(userId);
        if (session != null && session.isOpen()) {
            try {
                String notification = String.format(
                    "{\"taskId\":\"%s\",\"status\":\"%s\",\"message\":\"%s\",\"timestamp\":%d}",
                    taskId, status, message, System.currentTimeMillis()
                );
                session.getBasicRemote().sendText(notification);
                log.info("发送任务通知: userId={}, taskId={}, status={}", userId, taskId, status);
            } catch (IOException e) {
                log.error("发送WebSocket消息失败: userId={}", userId, e);
                userSessions.remove(userId);
            }
        } else {
            log.warn("用户WebSocket会话不存在或已关闭: userId={}", userId);
        }
    }

    /**
     * 广播任务通知给所有在线用户
     */
    public static void broadcastTaskNotification(String taskId, String status, String message) {
        String notification = String.format(
            "{\"taskId\":\"%s\",\"status\":\"%s\",\"message\":\"%s\",\"timestamp\":%d}",
            taskId, status, message, System.currentTimeMillis()
        );
        
        userSessions.entrySet().removeIf(entry -> {
            try {
                if (entry.getValue().isOpen()) {
                    entry.getValue().getBasicRemote().sendText(notification);
                    return false;
                }
            } catch (IOException e) {
                log.error("广播WebSocket消息失败: userId={}", entry.getKey(), e);
            }
            return true; // 移除无效会话
        });
        
        log.info("广播任务通知: taskId={}, status={}, 在线用户数={}", taskId, status, userSessions.size());
    }
}
